﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.BasicList
{
    public partial class frm_Edit_Part : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;

        public string part_no;

        public frm_Edit_Part()
        {
            InitializeComponent();

            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.part_no = null;

            LoadCustomer();
            LoadMaker();
            LoadSupplier();
            LoadIQ();
            LoadUnit();
            LoadPartClass();
            LoadCountry();
        }

        ////////////////////////////////////
        /// Load Customer List
        ///////////////////////////////////
        private void LoadCustomer()
        { 
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CustomerID"].ToString() + " | " + dataReader["FullName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Customer List");
            }             
        }

        ////////////////////////////////////
        /// Load Maker List
        ///////////////////////////////////
        private void LoadMaker()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MakerID, EnglishName FROM [222_Maker]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["MakerID"].ToString() + " | " + dataReader["EnglishName"].ToString();
                    item.Value = dataReader["MakerID"].ToString();
                    this.makerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Maker List");
            }
        }

        ////////////////////////////////////
        /// Load Supplier List
        ///////////////////////////////////
        private void LoadSupplier()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SupplierID, SupplierName FROM [222_Supplier]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierID"].ToString() + " | " + dataReader["SupplierName"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                    this.secondSupplier.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Supplier List");
            }
        }

        ////////////////////////////////////
        /// Load IQ List
        ///////////////////////////////////
        private void LoadIQ()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT IQID FROM [222_IQ]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["IQID"].ToString();
                    item.Value = dataReader["IQID"].ToString();
                    this.iqID.Properties.Items.Add(item);                    
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load IQ List");
            }
        }

        ////////////////////////////////////
        /// Load Unit List
        ///////////////////////////////////
        private void LoadUnit()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT UnitID, UnitNameEN FROM [222_Unit]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["UnitID"].ToString();
                    item.Value = dataReader["UnitNameEN"].ToString();
                    this.unitID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Unit List");
            }
        }

        ////////////////////////////////////
        /// Load Part Class
        ///////////////////////////////////
        private void LoadPartClass()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ClassID, ClassName FROM [222_PartClass]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ClassName"].ToString();
                    item.Value = dataReader["ClassID"].ToString();
                    this.unitID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Class List");
            }
        }
        
        ///////////////////////////////////
        /// Load Country List
        //////////////////////////////////
        private void LoadCountry()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CountryID, CountryName FROM [222_Country]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CountryName"].ToString();
                    item.Value = dataReader["CountryID"].ToString();
                    this.originalCountry.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Country List");
            }
        }


        ////////////////////////////////////
        /// Load data to form
        ///////////////////////////////////        
        public bool LoadData()
        { 
            bool ret = true;            
            if (string.IsNullOrEmpty(part_no))
            {
                ret = false;
            }
            else
            {
                try
                {
                    ComboboxItem item = new ComboboxItem();

                    myConnection.Open();
                    SqlCommand cmd_sql = myConnection.CreateCommand();
                    cmd_sql.CommandText = "SELECT * FROM [222_Part] WHERE PartNo='" + part_no + "'";
                    SqlDataReader dataReader = cmd_sql.ExecuteReader();
                    if (dataReader.Read())
                    {
                        this.partNo.Text = dataReader["PartNo"].ToString();
                        this.partPurchase.Text = dataReader["PartNoPurchase"].ToString();
                        this.partName.Text = dataReader["PartEnglishName"].ToString();
                        this.vietnamName.Text = dataReader["PartVietNamName"].ToString();
                        for (int i = 0; i < this.customerID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.customerID.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["MakerID"].ToString().ToUpper())
                            {
                                this.customerID.SelectedIndex = i;
                            }
                        }
                        
                        for (int i = 0; i < this.supplierID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.supplierID.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["SupplierID"].ToString().ToUpper())
                            {
                                this.supplierID.SelectedIndex = i;
                            }

                            item = (ComboboxItem)this.secondSupplier.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["SecondSupplierID"].ToString().ToUpper())
                            {
                                this.secondSupplier.SelectedIndex = i;
                            } 
                        }

                        for (int i = 0; i < this.iqID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.iqID.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["IQID"].ToString().ToUpper())
                            {
                                this.iqID.SelectedIndex = i;
                            }
                        }

                        for (int i = 0; i < this.unitID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.unitID.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["IQID"].ToString().ToUpper())
                            {
                                this.unitID.SelectedIndex = i;
                            }
                        }
                        
                        this.unitExchange.Text = dataReader["UnitExchange"].ToString();
                        this.leadTime.Text = dataReader["LeadTime"].ToString();
                        this.minQuantity.Text = dataReader["MinQuantity"].ToString();
                        this.materialValue.Text = dataReader["Material"].ToString();
                        this.partSize.Text = dataReader["PartSize"].ToString();
                        this.weightValue.Text = dataReader["Weight"].ToString();

                        if ((bool)dataReader["ROHS"])
                        {
                            this.roHS.Checked = true;
                        }

                        if ((bool)dataReader["ExportOrImport"])
                        {
                            this.exportCheck.Checked = true;
                        }

                        if ((bool)dataReader["QuantityBasePrice"])
                        {
                            this.quantityBasePrice.Checked = true;
                        }                        
                        this.safeQuantity.Text = dataReader["SafeQuantity"].ToString();
                        this.partType.Text = dataReader["PType"].ToString();

                        for (int i = 0; i < this.classID.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.classID.Properties.Items[i];
                            if (item.Value.ToString().ToUpper() == dataReader["Class"].ToString().ToUpper())
                            {
                                this.classID.SelectedIndex = i;
                            }
                        }                        

                        this.packingNote.Text = dataReader["PackingNote"].ToString();
                        for (int i = 0; i < this.originalCountry.Properties.Items.Count; i++)
                        {
                            item = (ComboboxItem)this.originalCountry.Properties.Items[i];
                            if (item.Value.ToString() == dataReader["OCountry"].ToString())
                            {
                                this.originalCountry.SelectedIndex = i;
                            }
                        }
                        this.marumeValue.Text = dataReader["Marume"].ToString();
                        this.departmentValue.Text = dataReader["Department"].ToString();
                        this.remarkValue.Text = dataReader["Remark"].ToString();                        
                    }
                    dataReader.Close();
                    cmd_sql.Dispose();
                    myConnection.Close();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    ret = false;
                }
            } 
            return ret; 
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
        
        private void buttonAdd_Click(object sender, EventArgs e)
        { 
            error = null;
            string part_purchase = null;
            string part_name = null;
            string vietnam_name = null;
            string customer = null;
            string maker = null;
            string supplier = null;
            string second_supplier = null;
            string iq_id = null;
            string unit_id = null;
            string unit_exchange = null;
            float exchange = 0;
            string lead_time = null;
            int leadtime = 0;
            string min_quantity = null;
            int min_qty = 0;
            string material = null;
            string part_size = null;
            float weight = 0;
            string part_weight = null;
            int export = 0;
            int rohs = 0;
            int qtybaseprice = 0;
            string safe_quantity = null;
            int safeqty = 0;
            string part_type = null;
            string classid = null;
            string packing_note = null;
            string original_country = null;
            string marume = null;
            int mar = 0;
            string department = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();

            part_purchase = this.partPurchase.Text;
            part_name = this.partName.Text;
            vietnam_name = vietnamName.Text;
            if (this.customerID.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.customerID.SelectedItem;
                customer = item.Value.ToString();
            }
            else
            {
                customer = "N99999";
            }
            if (this.makerID.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.makerID.SelectedItem;
                maker = item.Value.ToString();
            }
            else
            {
                maker = "E00000";
            }

            if (this.supplierID.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.supplierID.SelectedItem;
                supplier = item.Value.ToString();
            }
            else
            {
                supplier = "B99999";
            }

            if (this.secondSupplier.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.secondSupplier.SelectedItem;
                second_supplier = item.Value.ToString();
            }
            else
            {
                second_supplier = "B99999";
            }

            if (this.iqID.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.iqID.SelectedItem;
                iq_id = item.Value.ToString();
            }

            if (this.unitID.SelectedIndex >= 0)
            {
                item = (ComboboxItem)this.unitID.SelectedItem;
                unit_id = item.Value.ToString();
            }
            else
            {
                unit_id = "No";
            }

            if (!string.IsNullOrEmpty(this.unitExchange.Text))
            {
                if (float.TryParse(this.unitExchange.Text, out exchange))
                {
                    unit_exchange = this.unitExchange.Text;
                }
                else
                {
                    error = "Invalid Unit Exchange";
                }
            }
            else
            {
                unit_exchange = "NULL";
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!string.IsNullOrEmpty(this.leadTime.Text))
                {
                    if (Int32.TryParse(this.leadTime.Text, out leadtime))
                    {
                        lead_time = this.leadTime.Text;
                    }
                    else
                    {
                        error = "Invalid Lead Time";
                    }
                }
                else
                {
                    lead_time = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!string.IsNullOrEmpty(this.minQuantity.Text))
                {
                    if (Int32.TryParse(this.minQuantity.Text, out min_qty))
                    {
                        min_quantity = this.minQuantity.Text;
                    }
                    else
                    {
                        error = "Invalid Min Quantity";
                    }
                }
                else
                {
                    min_quantity = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                material = this.materialValue.Text;
                part_size = this.partSize.Text;

                if (!string.IsNullOrEmpty(this.weightValue.Text))
                {
                    if (float.TryParse(this.weightValue.Text, out weight))
                    {
                        part_weight = this.weightValue.Text;
                    }
                    else
                    {
                        error = "Invalid Weight";
                    }
                }
                else
                {
                    part_weight = "NULL";
                }
            }
            if (string.IsNullOrEmpty(error))
            {
                if (this.exportCheck.Checked)
                {
                    export = 1;
                }
                else
                {
                    export = 0;
                }

                if (this.roHS.Checked)
                {
                    rohs = 1;
                }
                else
                {
                    rohs = 0;
                }

                if (this.quantityBasePrice.Checked)
                {
                    qtybaseprice = 1;
                }
                else
                {
                    qtybaseprice = 0;
                }

                if (!string.IsNullOrEmpty(this.safeQuantity.Text))
                {
                    if (Int32.TryParse(this.safeQuantity.Text, out safeqty))
                    {
                        safe_quantity = this.safeQuantity.Text;
                    }
                    else
                    {
                        error = "Invalid Safe Quantity";
                    }
                }
                else
                {
                    safe_quantity = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                part_type = this.partType.Text;
                if (this.classID.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.classID.SelectedItem;
                    classid = item.Value.ToString();
                }
                else
                {
                    classid = "other";
                }
                
                packing_note = this.packingNote.Text;

                if (this.originalCountry.SelectedIndex >= 0)
                {
                    item = (ComboboxItem)this.originalCountry.SelectedItem;
                    original_country = item.Value.ToString();
                }
                else
                {
                    original_country = "18";
                }

                if (!string.IsNullOrEmpty(this.marumeValue.Text))
                {
                    if (Int32.TryParse(this.marumeValue.Text, out mar))
                    {
                        marume = this.marumeValue.Text;
                    }
                    else
                    {
                        error = "Invalid marume";
                    }
                }
                else
                {
                    marume = "NULL";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                department = this.departmentValue.Text;
                remark = this.remarkValue.Text;
                try
                {
                    myConnection.Open();
                    string sql = "UPDATE [222_Part] SET [PartNoPurchase] = '" + part_purchase + "',"
                        + " [PartEnglishName] = '" + part_name + "', [PartVietNamName] = N'" + vietnam_name + "',"
                        + " [CustomerID] = '" + customer + "', [MakerID] = '" + maker + "', [SupplierID] = '" + supplier + "',"
                        + " [SecondSupplierID] = '" + second_supplier + "', [IQID] = '" + iq_id + "', [UnitID] = '" + unit_id + "',"
                        + " [UnitExchange] = " + unit_exchange + ", [LeadTime] = " + lead_time + ","
                        + " [MinQuantity] = " + min_quantity + ", [ROHS] = " + rohs + ", [Material] = '" + material + "',"
                        + " [Weight] = " + part_weight + ", [PartSize] = '" + part_size + "',"
                        + " [QuantityBasePrice] = " + qtybaseprice + ", [ExportOrImport] = " + export + ","
                        + " [SafeQuantity] = " + safe_quantity + ", [PType] = '" + part_type + "', [Class] = '" + classid + "',"
                        + " [PackingNote] = '" + packing_note + "', [Remark] = '" + remark + "', [Marume] = " + marume + ","
                        + " [OCountry] = " + original_country + ", [Department] = '" + department + "'"
                        + " WHERE PartNo='" + part_no + "'";                    
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);                    
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Part updated success.");
                    this.Dispose();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot update Part. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }  
        }

    }
}
